package com.lx.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.ServletContext;

import freemarker.template.Configuration;
import freemarker.template.Template;
/**
 * 通过FreeMarker生成静态页面
 * @author liuxing
 *
 */
public class FRUtil {

	// 依赖ServletAPI创建的Configuration
	static Configuration cfgByServletContext = null;

	// 通过WebRoot位置来创建Configuration
	static Configuration cfgByWebRoot = null;

	// WebRoot路径，需要利用监听器来获取
	static String webRoot = null;

	/**
	 * 定时任务的配置，需要获取web项目根目录
	 * 
	 * @return
	 */
	private static Configuration getAutoOpCfg() {
		if (cfgByWebRoot == null) {
			try {
				cfgByWebRoot = new Configuration(Configuration.VERSION_2_3_23);
				webRoot = System.getProperty("webroot");
				cfgByWebRoot.setDirectoryForTemplateLoading(new File(webRoot + "/WEB-INF/ftl"));
				cfgByWebRoot.setDefaultEncoding("utf-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return cfgByWebRoot;
	}

	/**
	 * 获取手动配置的Configuration
	 * 
	 * @return
	 */
	private static Configuration getManOpCfg() {
		if (cfgByServletContext == null) {
			cfgByServletContext = new Configuration(Configuration.VERSION_2_3_23);
		}
		return cfgByServletContext;
	}

	/**
	 * 通过ServletContext获取模板来生成静态页面工具
	 * 
	 * @param ctx
	 *            ServletContext
	 * @param templateName
	 *            模板名
	 * @param dataModel
	 *            数据
	 * @param pageName
	 *            页面名
	 */
	public static void createPageByServletContext(ServletContext ctx, String templateName,
			Map<String, Object> dataModel, String pageName) {
		Configuration cfg = getManOpCfg();
		cfg.setServletContextForTemplateLoading(ctx, "/WEB-INF/ftl");
		cfg.setDefaultEncoding("utf-8");
		try {
			Template template = cfg.getTemplate(templateName);
			Writer out = new FileWriter(ctx.getRealPath("html/" + pageName));
			template.process(dataModel, out);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 通过监听器获取到的WebRoot目录来获取模板来创建页面，不需要依赖ServletAPI
	 * 
	 * @param templateName
	 * @param dataModel
	 * @param pageName
	 */
	public static void createPageByWebRoot(String templateName, Map<String, Object> dataModel, String pageName) {
		Configuration cfg = getAutoOpCfg();
		try {
			Template template = cfg.getTemplate(templateName);
			Writer out = new FileWriter(webRoot + "/html/" + pageName);
			String[] split = webRoot.split("/");
			String baseUrl = split[split.length - 1];
			dataModel.put("baseUrl", "/" + baseUrl);//用来在ftl页面中获取web项目根路径
			template.process(dataModel, out);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
